<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域-->
    <el-card>
      <!--添加角色按钮-->
      <el-row>
        <el-col>
          <el-button type="success" icon="el-icon-plus" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!--渲染商品分类列表数据-->
      <el-table :data="cateList" row-key="cat_id"
                :tree-props="cateTreeProps" border>
        <el-table-column label="#" type="index">
          <template v-slot="scope">{{ scope.row.index }}</template>
        </el-table-column>
        <el-table-column label="分类名称" prop="cat_name"></el-table-column>
        <el-table-column label="是否有效">
          <template v-slot="scope">
            <i v-if="!scope.row.cat_deleted" class="el-icon-check state-valid"></i>
            <i v-else class="el-icon-close state-failed"></i>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="cat_level">
          <template v-slot="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
            <el-tag type="warning" v-else-if="scope.row.cat_level === 2">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
          @size-change="cateSizeChange"
          @current-change="cateCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>


      <!--添加商品分类对话框-->
      <el-dialog
          title="添加商品分类"
          :visible.sync="addCateDialogVisible"
          width="30%"
          @close="addCateDialogClosed"
          :close-on-click-modal="false">
        <el-form ref="addCateForm" :model="addCateForm" :rules="addCateFormRules" label-width="80px">
          <el-form-item label="活动名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类" v-model="addCateForm.cat_pid">
            <el-cascader ref="cascader"
                v-model="selectCateKeys"
                :options="parentCateList"
                :props="{
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name',
                  checkStrictly: 'true'}"
                @change="parentCateChanged"
                clearable
            ></el-cascader>
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveCate">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类数据列表
      cateList: [],
      // 商品分类总记录数
      total: 0,
      // 商品数据属性参数
      cateTreeProps: {
        children: 'children',
        hacChildren: 'children'
      },
      addCateDialogVisible: false,
      // 添加商品分类实例
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      addCateFormRules: {
        cat_name: [
          {required: true, message: '请输入分类名称', trigger: 'blur'}
        ],
        cat_level: [
          {required: true, message: '请选择分类等级', trigger: 'blur'}
        ]
      },
      // 父级分类数据列表
      parentCateList: [],
      // 选中的父级分类 ID
      selectCateKeys: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const {data: res} = await this.$http.get('categories', {params: this.queryInfo})

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }

      this.cateList = res.data.result
      this.initIndex()
      this.total = res.data.total
      // console.log(res.data)
    },
    // 数目变化
    cateSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    // 当前页变化
    cateCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    // 自定义索引
    initIndex() {
      let preIdx = 0
      this.cateList.forEach(cate => {
        if (cate.cat_level === 0) {
          cate.index = preIdx + 1
          preIdx = cate.index
        }
      })
    },
    // 显示添加商品分类对话框
    showAddCateDialog() {

      this.getParentCateList()

      this.addCateDialogVisible = true
    },
    // 获取父级分类
    async getParentCateList() {
      const {data: res} = await this.$http.get('categories', {params: {type: 2}})
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败')
      }

      this.parentCateList = res.data
    },
    // 选择项发生变化后触发
    parentCateChanged() {

      // 检查 this.selectCateKeys 中的数组长度，来判断是否选中了父级分类
      if (this.selectCateKeys.length > 0) {
        this.addCateForm.cat_pid =
            this.selectCateKeys[this.selectCateKeys.length - 1]
      }else {
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      }
      // 分类的等级就等于已选中的 keys 的长度
      this.addCateForm.cat_level = this.selectCateKeys.length

      // console.log(this.addCateForm)
      // 点击之后将下拉界面收起来
      this.$refs.cascader.toggleDropDownVisible()
    },
    // 关闭添加商品分类对话框
    addCateDialogClosed() {
      this.$refs.addCateForm.resetFields()
      this.selectCateKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    // 保存分类信息
    async saveCate() {

      // console.log(this.addCateForm)
      const {data:res} = await this.$http.post('categories', this.addCateForm)
      if (res.meta.status !== 201) {
        return this.$message.error('保存商品分类信息失败')
      }

      this.$message.success('保存商品分类信息成功')
      this.getCateList()
      this.addCateDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.state-valid {
  color: #fff;
  font-size: 16px;
  border-radius: 50%;
  padding: 3px;
  background-color: #85ce61;
}

.state-failed {
  color: #fff;
  font-size: 16px;
  border-radius: 50%;
  padding: 3px;
  background-color: #F56C6C;
}


</style>